package com.ddsso.auth.web.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.ddsso.auth.web.repository.LoginDao;
import com.ddsso.auth.web.service.LoginService;

/**
 * @author zdd
 * @package com.ddsso.auth.service.impl
 * @Time Created by zdd on 2016/11/3.
 * @description To-do
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    // 反向会话放在 nkv 的 key 的前缀. 和其他业务的 key 分开
    private String backwardSessionKeyPrefix = "session.customerid.";

    // 正向会话放在 nkv 的 key 的前缀. 和其他业务的 key 分开
    // 必须和 framework-web 中的 NkvSessionDao.sessionKeyPrefix 一致
    private String forwardSessionKeyPrefix = "sessionid.";

    @Autowired
    @Qualifier("loginDao")
    private LoginDao loginDao;





    @Async
    public void syncSession(String customerId, String currentSessionId) {
        loginDao.syncSession(customerId,currentSessionId);
    }


    @Async
    public void invalidSession(String customerId, String excludedSessionId) {
        loginDao.invalidSession(customerId, excludedSessionId, getBackwardSessionKey(customerId), getForwardSessionKey(excludedSessionId));
    }

    /**
     * @description 删除记录的值
     * @param customerId
     */
    @Async
    public void delCustomerId(String customerId){
        loginDao.delCustomerId(customerId);
    }


    /********************************
     * @description  下面为服务的辅助类
     **********************************/
    private String md5(String sessionId) {
        return sessionId == null ? null : DigestUtils.md5Hex(sessionId);
    }
    private String getBackwardSessionKey(String customerId) {
        return backwardSessionKeyPrefix + customerId;
    }

    private String getForwardSessionKey(String sessionId) {
        return forwardSessionKeyPrefix + sessionId;
    }

}
